package cn.iocoder.yudao.module.liveprice.service;

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.module.liveprice.api.dto.LivePriceRespDTO;
import cn.iocoder.yudao.module.liveprice.apihttp.NowApiTypeEnum;
import cn.iocoder.yudao.module.liveprice.apihttp.dto.NowApiLivePriceDTO;
import cn.iocoder.yudao.module.liveprice.iotdb.IotDBConstants;
import cn.iocoder.yudao.module.liveprice.iotdb.dto.IotDbInsertDTO;
import cn.zhxu.okhttps.HttpResult;
import cn.zhxu.okhttps.OkHttps;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
@Service
@Slf4j
public class LivePriceApiServiceImpl implements LivePriceApiService {

    @Autowired
    private IotDbApiService iotDBApiService;
    @Override
    public LivePriceRespDTO getLivePriceAli() {
        String host = "https://autd.market.alicloudapi.com";
        String path = "/global/price";
        String method = "GET";
        String appcode = "你自己的AppCode";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("symbol", "GC");


        try {
            HttpResult.Body livePriceBody = OkHttps.sync(host + path)
                    .addBodyPara(querys)
                    .addHeader(headers)
                    .get()
                    .getBody()
                    .cache();
//            JSONObject userInfoJson = livePriceBody.toBean()
//            return BeanUtil.toBean(userInfoJson, OauthUserInfo.class);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public NowApiLivePriceDTO getLivePriceNowApi(Integer type) {
        String host = "https://sapi.k780.com/";
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("app", "finance.gold_price");
        querys.put("format", "json");
        querys.put("goldid", String.valueOf(type));
        querys.put("appkey", "73174");
        querys.put("sign", "57f6c9fa2161fe9604d6e21fdb180f82");
        try {
            HttpResult.Body livePriceBody = OkHttps.sync(host).addUrlPara(querys).get().getBody().cache();
            // 检查HTTP状态码
            try {
                JSONObject livePriceBodyJson = JSON.parseObject(livePriceBody.toString()); // 使用 parseObject 替代 toBean
                NowApiLivePriceDTO res = JSON.toJavaObject(
                        livePriceBodyJson.getJSONObject("result").getJSONObject("dtList").getJSONObject(String.valueOf(type)),
                        NowApiLivePriceDTO.class);
                nowApiInsertIotDb(res);
                return res;
                // 使用 nowApiLivePrice 做进一步处理
            } finally {
                livePriceBody.close(); // 确保关闭资源
            }
        } catch (Exception e) {
            // 处理可能的异常，例如网络问题或其他错误
            e.printStackTrace();
            log.info(String.valueOf(e));
        }
        return null;
    }

    /**
     * IoTdb数据库接口
     * 将接口数据转为iotdb数据存储
     */
    @Override
    public void nowApiInsertIotDb(NowApiLivePriceDTO apiDto) {
        IotDbInsertDTO insertDTO = new IotDbInsertDTO();
        List<IotDbInsertDTO.Item> items = new ArrayList<>(10);
        items.add(new IotDbInsertDTO.Item().setTag("price").setValue(apiDto.getLast_price()));
        items.add(new IotDbInsertDTO.Item().setTag("reclaim_price").setValue(apiDto.getBuy_price()));
        items.add(new IotDbInsertDTO.Item().setTag("seal_price").setValue(apiDto.getSell_price()));
        items.add(new IotDbInsertDTO.Item().setTag("high_price").setValue(apiDto.getHigh_price()));
        items.add(new IotDbInsertDTO.Item().setTag("low_price").setValue(apiDto.getLow_price()));
        items.add(new IotDbInsertDTO.Item().setTag("open_price").setValue(apiDto.getOpen_price()));
        items.add(new IotDbInsertDTO.Item().setTag("yesy_price").setValue(apiDto.getYesy_price()));
        items.add(new IotDbInsertDTO.Item().setTag("change_price").setValue(apiDto.getChange_price()));
        items.add(new IotDbInsertDTO.Item().setTag("change_margin").setValue(apiDto.getChange_margin().substring(0, apiDto.getChange_margin().length() - 1)));
        insertDTO.setData(items);
        insertDTO.setTimestamp(DateUtil.parse(apiDto.getUptime()).getTime());
        String path = IotDBConstants.PATH_REAL_PRICE + "." +
                Objects.requireNonNull(NowApiTypeEnum.getType(apiDto.getGoldid())).getTag();
        iotDBApiService.insert(path, insertDTO);
    }

}
